package com.atm.atmsys.Interceptor;

import com.atm.atmsys.context.BaseContext;
import com.atm.atmsys.utils.JwtUtil;
import com.atm.atmsys.utils.Result;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserLoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
        //登录校验
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //获取请求的url
        String url = req.getRequestURI();
        log.info("url:{}",url);

        //判断url中有没有login字段，有的话就放行
        if(url.contains("login")){
            log.info("登录操作，直接放行");
            return true;
        }

        //获取token
        String jwt=req.getHeader("token");
        System.out.println("jwt2:"+jwt);
        if(!StringUtils.hasLength(jwt)){
            log.info("token为空，请用户重新登录");
            Result.error("未登录");
            return false;
        }

        //解析token
        try{
            log.info("jwt校验：{}",jwt);
            Claims claims = JwtUtil.parseJWT(jwt);
            Long userid = Long.valueOf(claims.get("userId").toString());
            log.info("当前用户的Id:{}",userid);
            BaseContext.setCurrentId(userid);
        }catch (Exception e){
            e.printStackTrace();
            log.info("token解析失败，请重新登录");
            Result.error("未登录");
            return false;
        }
        //放行
        log.info("登录成功");
        return true;


    }


}
